package com.api.shop.util;

import com.api.shop.exception.ParamException;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.collections.MapUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.*;

public class BeanValidator {

    private static ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();

    /**
     *
     * @param t    验证某个bean的参数
     * @param groups    可变长参数
     * @param <T>    参数类型，此处用泛型表示
     * @return    返回验证信息
     */
    public static <T>Map<String, Object> validate(T t, Class ... groups){
        Validator validator = validatorFactory.getValidator();
        Set validateResult = validator.validate(t, groups);

        if(validateResult.isEmpty()){
            return Collections.emptyMap();
        }else{
            LinkedHashMap result = Maps.newLinkedHashMap();
            Iterator iterator = validateResult.iterator();

            while(iterator.hasNext()){
                ConstraintViolation violation = (ConstraintViolation) iterator.next();
                result.put(violation.getPropertyPath().toString(), violation.getMessage());
            }

            return result;
        }
    }

    public static Map<String, Object> validateList(Collection<?> collection) {
        Preconditions.checkNotNull(collection);
        Iterator iterator = collection.iterator();
        Map errors;

        do {
            if (!iterator.hasNext()) {
                return Collections.emptyMap();
            }
            Object object = iterator.next();
            errors = validate(object, new Class[0]);
        } while (errors.isEmpty());

        return errors;
    }

    public static Map<String, Object> validateObject(Object first, Object... objects) {
        if (objects != null && objects.length > 0) {
            return validateList(Lists.asList(first, objects));
        } else {
            return validate(first, new Class[0]);
        }
    }

    public static void check(Object param) throws ParamException {
        Map<String, Object> map = BeanValidator.validateObject(param);
        if (MapUtils.isNotEmpty(map)) {
            throw new ParamException(map.toString());
        }
    }

}
